using UnityEngine;
using UnityEditor;
using System.Diagnostics;
using System.IO;
using UMPRelease;

public class GitSyncDialog : EditorWindow
{
    private GitHandleData gitData;
    private PackageData packageConfig;

    // [MenuItem("UMP Release/Sync Branch and Tag Dialog")]
    public static void ShowDialog()
    {
        GitSyncDialog window = GetWindow<GitSyncDialog>("Git Sync Dialog");
        window.minSize = new Vector2(400, 300);
        var data = AssetDatabase.LoadAssetAtPath<VersionHandle>(UMPReleaseEditor.DefaultPath);
        if (data != null)
        {
            window.gitData = data.SyncGit;
            window.packageConfig = data.PackageConfig;
            window.Show();
        }
    }

    void OnGUI()
    {
        GUILayout.Label("Git 分支和标签同步", EditorStyles.boldLabel);
        EditorGUILayout.Space();

        gitData.remoteName = EditorGUILayout.TextField("远程仓库", gitData.remoteName);
        gitData.sourceBranch = EditorGUILayout.TextField("源分支", gitData.sourceBranch);
        gitData.targetBranch = EditorGUILayout.TextField("目标分支", gitData.targetBranch);
        gitData.tagName = EditorGUILayout.TextField("标签名称", gitData.tagName);
        packageConfig.name = EditorGUILayout.TextField("包名", packageConfig.name);
        gitData.commitMessage = EditorGUILayout.TextField("提交信息", gitData.commitMessage);

        EditorGUILayout.Space();

        if (GUILayout.Button("执行同步", GUILayout.Height(30)))
        {
            if (ValidateInputs())
            {
                GitSyncAPI.SyncBranchAndTag(gitData.remoteName, 
                gitData.sourceBranch, 
                gitData.targetBranch, 
                gitData.tagName, 
                packageConfig.name, 
                gitData.commitMessage);
                Close();
            }
        }

        EditorGUILayout.Space();

        if (GUILayout.Button("取消"))
        {
            Close();
        }
    }

    private bool ValidateInputs()
    {
        if (string.IsNullOrEmpty(gitData.remoteName))
        {
            EditorUtility.DisplayDialog("错误", "远程仓库名称不能为空", "确定");
            return false;
        }

        if (string.IsNullOrEmpty(gitData.targetBranch))
        {
            EditorUtility.DisplayDialog("错误", "目标分支不能为空", "确定");
            return false;
        }

        if (string.IsNullOrEmpty(gitData.tagName))
        {
            EditorUtility.DisplayDialog("错误", "标签名称不能为空", "确定");
            return false;
        }

        return true;
    }
}

public class GitSyncAPI
{
    // [MenuItem("UMP Release/Sync Branch and Tag")]
    public static void SyncBranchAndTag()
    {
        SyncBranchAndTag("origin", "master", "upm", "v1.0.0", "com.bear.package", "--");
    }

    [MenuItem("UMP Release/Sync Branch and Tag (Custom)")]
    public static void SyncBranchAndTagCustom()
    {
        GitSyncDialog.ShowDialog();
    }

    public static void SyncBranchAndTag(string remoteName, string sourceBranch, string targetBranch, string tagName, string packagePath, string commitMessage)
    {
        string projectPath = Application.dataPath.Replace("/Assets", "");
        string scriptPath = Path.Combine(projectPath, "sync_branch_and_tag.ps1");

        if (!File.Exists(scriptPath))
        {
            EditorUtility.DisplayDialog("错误", "找不到 sync_branch_and_tag.ps1 脚本", "确定");
            return;
        }

        // 构建 PowerShell 命令
        string arguments = $"-ExecutionPolicy Bypass -File \"{scriptPath}\" -RemoteName \"{remoteName}\" -SourceBranch \"{sourceBranch}\" -TargetBranch \"{targetBranch}\" -TagName \"{tagName}\" -PackagePath \"{packagePath}\" -CommitMessage \"{commitMessage}\"";

        // 执行 PowerShell 脚本
        ExecutePowerShellScript(arguments);
    }

    private static void SetExecutablePermission(string scriptPath)
    {
        if (Application.platform == RuntimePlatform.WindowsEditor)
        {
            // Windows 不需要设置权限
            return;
        }

        // Unix/Linux/macOS 设置执行权限
        ProcessStartInfo chmodInfo = new ProcessStartInfo
        {
            FileName = "chmod",
            Arguments = $"+x \"{scriptPath}\"",
            UseShellExecute = false,
            CreateNoWindow = true
        };

        using (Process chmodProcess = Process.Start(chmodInfo))
        {
            chmodProcess?.WaitForExit();
        }
    }

    private static void ExecutePowerShellScript(string arguments)
    {
        ProcessStartInfo startInfo = new ProcessStartInfo
        {
            FileName = "powershell.exe",
            Arguments = arguments,
            UseShellExecute = false,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            CreateNoWindow = true,
            WorkingDirectory = Application.dataPath.Replace("/Assets", "")
        };

        using (Process process = Process.Start(startInfo))
        {
            if (process != null)
            {
                string output = process.StandardOutput.ReadToEnd();
                string error = process.StandardError.ReadToEnd();

                process.WaitForExit();

                if (process.ExitCode == 0)
                {
                    UnityEngine.Debug.Log($"Git 同步成功:\n{output}");
                    EditorUtility.DisplayDialog("成功", "分支和标签同步完成", "确定");
                }
                else
                {
                    UnityEngine.Debug.LogError($"Git 同步失败:\n{error}");
                    EditorUtility.DisplayDialog("错误", $"Git 同步失败:\n{error}", "确定");
                }
            }
        }
    }
}